<script setup lang="ts">
import {getCurrentInstance, reactive, ref} from "vue";
import {Message} from "@arco-design/web-vue";
import {imageListAxios, type ImagesListRsp} from "@/api/image_api";
import {advertAddAxios, type AdvertAddReq} from "@/api/promotion_api";

const visible = ref(false);

const mitt = getCurrentInstance()

mitt?.proxy?.$Bus.on('openAddModal', () => {
  visible.value = true
})

const form = reactive<AdvertAddReq>({
  title: "",
  image: "",
  href: "",
  is_show: false,
})

const formRef = ref()

const imageList = ref<ImagesListRsp[]>([])

async function addAvert() {
  // val是undefined则表示校验通过
  let val = await formRef.value.validate()
  if (val) {
    return false
  }
  let rsp = await advertAddAxios(form);
  if (rsp.code !== 0) {
    Message.error("添加失败")
    return false
  }
  Message.success("添加成功")
  mitt?.proxy?.$Bus.emit("refresh")
  close()
}

function close() {
  visible.value = false
  formReset()
}

function formReset() {
  formRef.value.resetFields(Object.keys(form))
  formRef.value.clearValidate(Object.keys(form))
}

async function queryImageList() {
  let list = await imageListAxios({page: 1, limit: 1000});
  imageList.value = list.data.list
}

queryImageList()
</script>

<template>
  <a-modal title="创建广告" :visible="visible" :on-before-ok="addAvert" @cancel="close">
    <a-form
        ref="formRef"
        :model="form">

      <a-form-item field="title" label="广告名称" :rules="[{required:true,message:'请输入广告名称'}]"
                   validate-trigger="blur">
        <a-input v-model="form.title" placeholder="广告名称"></a-input>
      </a-form-item>

      <a-form-item field="href" label="跳转链接" :rules="[{required:true,message:'请输入广告链接'}]"
                   validate-trigger="blur">
        <a-input v-model="form.image" placeholder="广告链接"></a-input>
      </a-form-item>

      <a-form-item field="image" label="图片路劲">
        <a-input v-model="form.href" placeholder="图片路劲"></a-input>
      </a-form-item>

      <a-form-item field="image" label="图片预览">
        <a-input v-model="form.href" placeholder="广告链接"></a-input>
      </a-form-item>

      <a-form-item field="is_show" label="是否显示">
        <a-resize-box v-model="form.is_show" placeholder="是否显示"></a-resize-box>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<style lang="scss">

</style>
